package demo.matrixarray;

import java.util.Arrays;

/**
 * 旋转打印问题
 */
public class PrintMatrixSpiralOrder {

    public static void main(String[] args) {
      /* int[][] matrix = {
                {1, 2, 3, 4, 5, 6, 7},
                {8, 9, 10, 11, 12, 13, 14},
                {15, 16, 17, 18, 19, 20, 21},
                {22, 23, 24, 25, 26, 27, 28}
        };*/

        int[][] matrix = {
                {1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12},
                {13, 14, 15, 16}
        };

        for (int i = 0; i < matrix.length; i++) {
            System.out.println(Arrays.toString(matrix[i]));
        }
        spiralOrderPrint(matrix);
        System.out.println();
    }

    public static void spiralOrderPrint(int[][] matrix) {
        // 我们自己找两个点，用于确定第一圈
        int aX = 0;
        int aY = 0;
        // b点，我们用二维数组的大小来确定最右下角的坐标
        int bX = matrix.length - 1;
        int bY = matrix[0].length - 1;
        // 第一圈循环完了再循环第二圈，当a点的x轴大于b点的x轴，并且a的y大于b的y时，说明已经全部扫描一圈了
        while (aX <= bX && aY <= bY) {
            printEdge(matrix, aX++, aY++, bX--, bY--);
        }
    }

    public static void printEdge(int[][] m, int aX, int aY, int bX, int bY) {
        if (aX == bX) {
            // a,b点的横坐标相同，说明这个矩阵就一行了
            for (int i = aY; i <= bY; i++) {
                System.out.print(m[aX][i] + " ");
            }
        } else if (aY == bY) {
            // a,b点的纵坐标相同，这个矩阵就只有一列了
            for (int i = aX; i <= bX; i++) {
                System.out.print(m[i][aY] + " ");
            }
        } else {
            int curX = aX;
            int curY = aY;
            while (curX != bX) {
                System.out.print(m[aX][curX] + " ");
                curX++;
            }
            while (curY != bY) {
                System.out.print(m[curY][bX] + " ");
                curY++;
            }
            while (curX != aX) {
                System.out.print(m[bY][curX] + " ");
                curX--;
            }
            while (curY != aY) {
                System.out.print(m[curY][aY] + " ");
                curY--;
            }
        }
    }


}
